<?php


namespace Plugin\PaypalSiteB;

use Beike\Models\Country;
use Beike\Models\OrderPayment;
use Beike\Models\OrderShipment;
use Beike\Services\StateMachineService;
use Illuminate\Support\Facades\Log;
use Matrix\Exception;
use Plugin\LK5Shipping\Models\K5Channel;
use Plugin\LK5Shipping\Models\K5ChannelOrder;
use Plugin\LK5Shipping\Models\K5ChannelSkuWeight;
use Plugin\Paypal\Services\PaypalService;
use Plugin\PaypalSiteB\Models\PaypalSiteAOrder;
use Plugin\PaypalSiteB\Models\PayProductName;
use Plugin\PaypalSiteB\Services\PollingPaypalTools;

class Bootstrap
{
    public function boot()
    {

        add_hook_filter('service.payment.mobile_pay.data', function ($data) {
            if ($data['order']->payment_method_code == 'paypal_site_b') {
                $pollingPaypalTools = new PollingPaypalTools();
                $settings           = $pollingPaypalTools->getPollingSetting($data['order']->number);
                if (empty($settings)) {
                    die("请先配置支付帐户");
                }
                $data['payment_setting'] = $settings;

                //判断是不是使用了ab,是的话，则要进行下面这个界面来显示
                $siteAorder = PaypalSiteAOrder::query()->where('order_no', $data['order']->number)->first();
                if ($siteAorder) {
                    $data['pay_url'] = shop_route('paypal_s.pay_order', ['order_no' => $data['order']->number]);
                    echo view('PaypalSiteB::checkout.payment_site_b', $data);
                    exit;
                }
            }
        });

        add_hook_blade('admin.plugin.form', function ($callback, $output, $data) {
            $code = $data['plugin']->code;
            if ($code == 'paypal_site_b') {
                return view('PaypalSiteB::admin.config_form', $data)->render();
            }
            return $output;
        }, 2000194);

        add_hook_filter('service.payment.pay.data', function ($data) {
            if ($data['order']->payment_method_code == 'paypal_site_b') {
                $pollingPaypalTools = new PollingPaypalTools();
                $settings           = $pollingPaypalTools->getPollingSetting($data['order']->number);
                if (empty($settings)) {
                    die("请先配置支付帐户");
                }
                $data['payment_setting'] = $settings;

                //判断是不是使用了ab,是的话，则要进行下面这个界面来显示
                $siteAorder = PaypalSiteAOrder::query()->where('order_no', $data['order']->number)->first();
                if ($siteAorder) {
                    $data['pay_url'] = shop_route('paypal_s.pay_order', ['order_no' => $data['order']->number]);
                    echo view('PaypalSiteB::checkout.payment_site_b', $data);
                    exit;
                }
            }

            return $data;
        }, 2000194);


        //支付后要执行推送订单到A站
        add_hook_filter('service.state_machine.machines', function ($data) {
            $data['machines'][StateMachineService::UNPAID][StateMachineService::PAID][] = function () use ($data) {
                //检测是否要推送给a站
                $siteAorder = PaypalSiteAOrder::query()->where('order_no', $data['order']->number)->first();
                if ($siteAorder) {
                    $pollingPaypalTools = new PollingPaypalTools();
                    $pollingPaypalTools->pushToASite($data['order']->number, StateMachineService::PAID);
                }
            };

            return $data;
        });

        //订单列表加入标识
        add_hook_filter('admin.order.index.data', function ($data) {
            $orders  = $data['orders'];
            $numbers = [];
            foreach ($orders as $order) {
                $numbers[] = $order->number;
            }
            $order_nos = PaypalSiteAOrder::query()->whereIn('order_no', $numbers)->get()->pluck('order_no')->toArray();

            foreach ($orders as $order) {
                if (in_array($order->number, $order_nos)) {
                    $order->number = $order->number . '-A站';
                }
            }
            return $data;
        });


        add_hook_filter('admin.product.form.data', function ($data) {
            $product           = $data['product'];
            $paypalProductName = PayProductName::query()->where("product_id", $product->id)->first();
            if ($paypalProductName) {
                $product->pay_product_name = $paypalProductName->product_name;
            } else {
                $product->pay_product_name = '';
            }
            return $data;
        }, 2000194);

        add_hook_blade("admin.product.name.after", function ($callback, $output, $data) {
            $view = view('PaypalSiteB::admin.product_name', $data)->render();
            return $view . $output;
        }, 2000194);

        add_hook_action('admin.product.store.after', function ($data) {
            $product      = $data['product'];
            $request_data = $data['request_data'];
            $this->updatePayProductName($product, $request_data);

            return $data;
        }, 2000194);

        add_hook_action('admin.product.update.after', function ($data) {
            $product      = $data['product'];
            $request_data = $data['request_data'];
            $this->updatePayProductName($product, $request_data);
            return $data;
        }, 2000194);


        /**
         * 发货同步物流单号到paypal
         */
        add_hook_filter('service.state_machine.machines', function ($data) {

            $order = $data['order'];
            if ($order->payment_method_code == 'paypal_site_b') {
                $sendPaypalOrderShipping = function () use ($order) {
                    $orderShipment = request()->all();

                    $expressCompanies = system_setting('base.express_company');
                    $tmpExpress       = [];
                    if (!empty($expressCompanies)) {
                        foreach ($expressCompanies as $expressCompanie) {
                            $tmpExpress[$expressCompanie['code']] = $expressCompanie['name'];
                        }
                    }

                    $express_code   = $orderShipment['express_code'];
                    $express_number = $orderShipment['express_number'];

                    $orderPayment = OrderPayment::query()->where('order_id', $order->id)->first();
                    if ($orderPayment) {
                        $response           = json_decode($orderPayment->response, true);
                        $transactionId      = $response['purchase_units'][0]['payments']['captures'][0]['id'];
                        $pollingPaypalTools = new PollingPaypalTools();
                        if ($transactionId) {
                            $notify = request()->get('notify');
                            $rs     = $pollingPaypalTools->uploadExpressInfo($order, $transactionId, $express_number, $tmpExpress[$express_code], $notify ? $notify : true);
                            if (!$rs) {
                                throw new Exception("上传物流单号失败(1)");
                            }
                        }
                    }
                };
                array_unshift($data['machines'][StateMachineService::PAID][StateMachineService::SHIPPED], $sendPaypalOrderShipping);
            }
            return $data;
        });


    }


    private function updatePayProductName($product, $request_data)
    {
        $productId         = $product->id;
        $pay_product_name  = $request_data['pay_product_name'];
        $paypalProductName = PayProductName::query()->where("product_id", $product->id)->first();
        if ($paypalProductName) {
            $paypalProductName->product_name = $pay_product_name;
            $paypalProductName->update();
        } else {
            $saveData = [
                'product_id'   => $productId,
                'product_name' => $pay_product_name,
            ];
            PayProductName::query()->insert($saveData);
        }
    }
}
